<template>
  <div>
    <el-dialog
      ref="serviceDialog"
      class="pms-zr-dialog"
      :title="parentRow.editable ? '配置明细' : '配置明细查看'"
      :visible.sync="dialogVisible"
      width="90%"
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <p v-if="parentRow.editable" class="new-title" style="margin-top: -5px;color: #EB4B4B;font-size: 12px;">组合件为“是”的施工总承包、外电引入施工服务下必须据实包含乙供主设备或辅材，若实际不存在乙供主设备或辅材，请进行设计变更选择组合件为“否”的服务编码</p>
      <div v-if="parentRow.editable" class="selectList">
        <!-- <AccTitle /> -->
        <el-form ref="form" :inline="true" :model="form" label-width="200px" class="select-form">
          <el-form-item label="物料编码：">
            <el-input v-model.trim="form.materialCode" placeholder="请输入..." />
          </el-form-item>
          <el-form-item label="物料名称：">
            <el-input v-model.trim="form.materialName" placeholder="请输入..." />
          </el-form-item>
          <div class="operate-btn-group">
            <el-button class="pms-zr-button-primary" size="small" @click="handleQuery">查询</el-button>
            <el-button
              :loading="loading"
              class="pms-zr-button-primary"
              style="margin-left: 10px !important;"
              size="small"
              @click="handleAdd"
            >添加</el-button>
          </div>
        </el-form>
        <el-table ref="table" v-loading="loading" :data="tableData" border @selection-change="handleSelectionChange">
          <el-table-column align="center" width="40" type="selection" />
          <el-table-column align="center" type="index" width="70" label="序号">
            <template slot-scope="scope">
              {{ scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="materialCode" label="物料编码" width="200" />
          <el-table-column align="center" prop="materialName" label="物料名称" show-overflow-tooltip />
          <el-table-column align="center" prop="spuMainName" width="160" label="主设备标识" show-overflow-tooltip/>
          <el-table-column align="center" prop="ifSourceName" width="200" label="源头赋码标识" />
        </el-table>
        <pagination
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <div v-if="parentRow.editable" class="operate-btn-group">
        <el-button class="pms-zr-button-primary" size="small" @click="handleOpenIllustrate">填写说明</el-button>
        <!-- <el-button class="pms-button-primary operate-btn">批量导入</el-button> -->
        <el-button
          class="pms-zr-button-primary"
          style="margin-left: 10px !important;"
          size="small"
          @click="handleSave"
        >保存</el-button>
      </div>
      <div class="itemTrading" style="max-height: 300px;overflow: auto">
        <el-table
          id="serviceConfigTable"
          ref="addTable"
          :data="addTableData"
          border
          class="inputTable"
          row-key="id"
          show-summary
          :summary-method="summaryMethods"
          :tree-props="{ children: 'childrenData', hasChildren: 'needFolded' }"
        >
          <el-table-column align="center" type="index" width="70" label="序号">
            <template slot-scope="scope">
              {{ scope.row.diyIndex }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="spuMainCode" width="160" label="主设备标识" :formatter="shineAsk" show-overflow-tooltip/>
          <el-table-column align="center" prop="detailMaterialCode" label="明细物料编码" width="130" />
          <el-table-column align="center" prop="detailMaterialName" label="明细物料名称" width="370" show-overflow-tooltip/>
          <el-table-column align="center" prop="detailNum" label="数量">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.parent && parentRow.editable"
                v-model.trim="scope.row.detailNum"
                :disabled="ynEditquDisAble(scope.row, 'detailNum')"
                @input="storemanNumInput($event, scope, 'detailNum')"
              />
              <span v-else>{{ scope.row.detailNum }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="detailProportion" label="占比(%)">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.parent && parentRow.editable"
                v-model.trim="scope.row.detailProportion"
                :disabled="ynEditquDisAble(scope.row, 'detailProportion')"
                @input="storemanNumInput($event, scope, 'detailProportion')"
              />
              <span v-else>{{ scope.row.detailProportion }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="detailMoney" label="金额" />
          <el-table-column align="center" prop="requiredLabelNum" width="110" label="需赋码贴签数量" />
          <el-table-column align="center" prop="sourceAssetCode" width="110" label="资源资产编码" />
          <el-table-column align="center" prop="labelId" width="110" label="标签ID" />
          <el-table-column v-if="parentRow.editable" align="center" width="120" label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="!(scope.row.parent && +scope.row.hideDeleteSign === 1)"
                size="small"
                class="pms-zr-button-primary"
                style="margin-right: 10px !important;"
                @click="handleDelete(scope)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <dialog-confirm v-if="visible" :message="['确认删除该明细']" @changeStatus="handleDelAxios2" />
    <DialogConfirmQuRen v-if="querenvisible" :message="['已配置明细占比之和不为100%,请确认是否保存']" @changeStatus="querenClick" />
    <Illustrate ref="Illustrate" :open="open" />
  </div>
</template>

<script>
// import AccTitle from './title/accTitle'
import Illustrate from './title/illustrate'
import { deepCopy, enableScroll, msgInfoEl } from '@/utils'
import { shineAsk, childData, inputValidation, chZnNumber } from './common'
import {
  getDetails,
  getSelectedServiceDetailList,
  addMaterialDetail,
  deleteMaterialDetail,
  saveDetails,
} from '@/api/acceptanceManagement'
import DialogConfirm from '@/views/acceptanceManagement/materialServiceBind/components/dialogConfirm.vue'
import DialogConfirmQuRen from '@/views/acceptanceManagement/materialServiceBind/components/dialogConfirm.vue'
export default {
  components: { DialogConfirm, Illustrate, DialogConfirmQuRen },
  data() {
    return {
      querenvisible: false,
      dialogVisible: false,
      open: false,
      form: {},
      tableData: [],
      total: 0,
      // 分页信息
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      addTableData: [],
      beforeAddTableData: [],
      activeName: '1',
      parentRow: {},
      selectRow: [],
      loading: false,
      addLoading: false,
      rules: [],
      visible: false,
      saveObj: {
        urls: '',
        objdata: {}
      }
    }
  },
  watch: {
    addTableData: { // 表格数据
      immediate: true,
      handler() {
        setTimeout(() => {
          // const tds = document.querySelectorAll('#table .el-table__footer-wrapper tr>td');//表格没有固定列时 写法
          const tds = document.querySelectorAll('#serviceConfigTable .el-table__footer-wrapper tr>td')// 表格有固定列时 写法
          tds[0].colSpan = 4
          tds[0].style.textAlign = 'center'
          tds[1].style.display = 'none'
          tds[2].style.display = 'none'
          tds[3].style.display = 'none'
        }, 0)
      }
    }
  },
  methods: {
    // 打开弹窗
    async getRow(val) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.dialogEl('serviceDialog')
      })
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.form = {}
      this.parentRow = val
      this.getList()
      this.getAddList()
    },
    dialogEl(refName) {
      // 将弹框挂载在最外层
      const contentBody = window.top.document.body
      this.$nextTick(() => {
        const dialogModal = document.querySelector('.v-modal')
        console.log({ dialogModal })
        const elBody = this.$refs[refName].$el
        dialogModal.style.zIndex = 3000
        elBody.style.zIndex = 3001
        contentBody.appendChild(elBody)
        contentBody.appendChild(dialogModal)
        // disableScroll(contentBody)
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 查询上方表格
    async getList() {
      this.loading = true
      const obj = {
        prjId: this.parentRow.prjId,
        subPrjId: this.parentRow.subPrjId,
        serviceCode: this.parentRow.pmsServiceCode,
        type: this.parentRow.type,
        ...this.form,
        ...this.queryParams
      }
      const { data } = await getDetails(obj)
      this.tableData = data.rows
      this.total = data.total
      this.loading = false
      // 更新接口
      this.$emit('refreshTable', this.parentRow.typeIndex)
    },
    // 下方表格
    async getAddList() {
      this.addLoading = true
      const obj = {
        prjId: this.parentRow.prjId,
        subPrjId: this.parentRow.subPrjId,
        materialCode: this.parentRow.pmsServiceCode,
        type: this.parentRow.type,
        isPilot: this.parentRow.urlParams.type === '4' ? 0 : this.parentRow.urlParams.isWhite ? 0 : this.parentRow.urlParams.isPilot // 回滚原逻辑
      }
      const res = await getSelectedServiceDetailList(obj)
      const data = childData(res.data).map((item, index) => {
        return {
          ...item,
          diyIndex: index + 1
        }
      })
      this.addTableData = data
      this.beforeAddTableData = deepCopy(data)
      this.addLoading = false
      this.$nextTick(() => {
        this.$refs['addTable'].doLayout()
      })
    },
    handleSelectionChange(row) {
      this.selectRow = row
    },
    // 添加
    async handleAdd() {
      if (this.selectRow.length < 1) {
        return msgInfoEl({
          type: 'warning',
          message: '请选择数据'
        })
      }
      const obj = {
        prjId: this.parentRow.prjId,
        subPrjId: this.parentRow.subPrjId,
        materialCode: this.parentRow.pmsServiceCode,
        siteId: this.parentRow.siteId,
        type: this.parentRow.type,
        details: this.selectRow
      }
      // 判断是否是销项阶段
      const url = this.parentRow.urlParams.type !== '4' ? 'addMaterialDetail' : 'addMaterialDetailRevocation'
      const res = await addMaterialDetail(obj, url)
      if (+res.code === 200) {
        msgInfoEl({
          type: 'success',
          message: res.message
        })
      }
      this.getList()
      this.getAddList()
    },
    storemanNumInput(val, row, name) {
      const data = row.row
      const value = val - 0

      if (name === 'detailNum') {
        console.log(inputValidation(value, data),value,data,val,"打印");
        if (!inputValidation(value, data)) {
          data[name] = ''
          if (data.spuUnitAcc === '0') {
            return msgInfoEl({
              type: 'warning',
              message: `明细物料编码为${data.detailMaterialCode}的数量可填写到整数`
            })
          } else {
            return msgInfoEl({
              type: 'warning',
              message: `明细物料编码为${data.detailMaterialCode}的数量可填写到小数点后${chZnNumber[data.spuUnitAcc]}位`
            })
          }
        } else {
          // data[name] = inputValidation(value, data)[0] - 0
          data[name] = val
        }
      }
      if (name === 'detailProportion') {
        // const va = `${value}`.match(/^[0-9]+(\.[0-9]{0,2})?$/)
        const va = (/^[0-9]+(\.[0-9]{0,2})?$/).test(`${value}`)
        if (!va) {
          data[name] = 0
          return msgInfoEl({
            type: 'warning',
            message: '占比只能填写数字且可填写到小数点后二位'
          })
        } else {
          data[name] = val
        }
      }
    },
    // 删除
    handleDelete(val) {
      const row = val.row
      console.log(this.beforeAddTableData, val, '===>')
      if (row.parent && !this.beforeAddTableData[row.id].detailNum) {
        this.handleDelAxios(row)
        return
      }
      if (row.isLabel === '0') {
        if (!row.parent) {
          const arr = row.id.split('-')
          const table = deepCopy(this.addTableData)
          table[arr[0]].deletedSubDetailId = table[arr[0]].childrenData[arr[1]].detailId
          return this.handleDelAxios(table[arr[0]])
        }
        if (row.parent && !row.needFolded && row.requiredLabelNum !== null && row.requiredLabelNum < this.beforeAddTableData[row.id].detailNum) {
          msgInfoEl({
            type: 'warning',
            message: '已有赋码贴签数据，请到列表中删除具体所操作的数据！'
          })
        } else {
          this.handleDelAxios(row)
        }
        // if (row.parent && !row.needFolded && row.requiredLabelNum === this.beforeAddTableData[val.$index].detailNum) {
        // } else {
        //   this.$message.warning('已有数码贴签数据，请到列表中删除具体所操作的数据！')
        // }
      } else {
        this.handleDelAxios(row)
      }
    },
    // 删除axios
    handleDelAxios(row) {
      this.row = row
      this.visible = true
    },
    // 删除axios
    async handleDelAxios2(check) {
      this.visible = false
      if (!check) {
        return
      }
      delete this.row.childrenData
      const url = this.parentRow.urlParams.type === '4' ? 'deleteMaterialDetailRevocation' : 'deleteMaterialDetail'
      const res = await deleteMaterialDetail(this.row, url)
      if (+res.code === 200) {
        msgInfoEl({
          type: 'success',
          message: res.message
        })
      }
      this.getList()
      this.getAddList()
    },
    // 2021/10/29阻断修复
    async optimizeNewhandleSaveOne(b) {
      if (!b) {
        msgInfoEl({
          type: 'error',
          message: '数量不能为空'
        })
        return Promise.reject()
      }
    },
    async optimizeNewhandleSaveTwo(a) {
      if (!a) {
        msgInfoEl({
          type: 'error',
          message: '占比不能为空'
        })
        return Promise.reject()
      }
    },
    async optimizeNewhandleSaveThree(boo) {
      if (!boo) {
        return Promise.reject()
      }
    },
    async optimizeNewhandleSaveFour(trueNumBoo) {
      if (!trueNumBoo) {
        msgInfoEl({
          type: 'error',
          message: '该物资下存在已贴签数据，请手动在明细中进行删除'
        })
        return Promise.reject()
      }
    },
    async optimizeNewhandleSaveFive(data) {
      if (this.addTableDataRules(data)) {
        return Promise.reject()
      }
    },
    async optimizeNewhandleSaveSix(yueshu) {
      if (yueshu !== 100) {
        this.querenvisible = true
        return Promise.reject()
      }
    },
    async optimizeNewhandleSaveSeven(resSave) {
      if (+resSave.code === 4120) {
        this.getList()
        this.getAddList()
        return Promise.reject()
      }
      if (resSave.code !== '200') {
        return Promise.reject()
      }
    },
    async optimizeNewhandleSaveEight() {
      return this.parentRow.urlParams.type === '4' ? 'saveServiceDetailsDataRevocation' : 'saveServiceDetailsData'
    },
    // 保存
    async handleSave() {
      let a = true
      let b = true
      const data = this.addTableData.map(item => {
        if (!item.detailProportion) {
          a = false
        }
        if (!item.detailNum) {
          b = false
        }
        return item.detailProportion
      })
      await this.optimizeNewhandleSaveOne(b)
      await this.optimizeNewhandleSaveTwo(a)
      // if (!b) {
      //   return msgInfoEl({
      //     type: 'error',
      //     message: '数量不能为空'
      //   })
      // }
      // if (!a) {
      //   return msgInfoEl({
      //     type: 'error',
      //     message: '占比不能为空'
      //   })
      // }

      const boo = this.addTableData.every(item => {
        for (const name in item) {
          if (['detailNum', 'detailProportion'].includes(name)) {
            return !this.saveRules(item[name], item, name)
          }
        }
      })
      await this.optimizeNewhandleSaveThree(boo)
      // if (!boo) {
      //   return
      // }
      let trueNumBoo = true
      this.beforeAddTableData.map((item, index) => {
        if (item.isLabel === '0' && item.parent && !item.needFolded) {
          const trueNum = Number(item.detailNum) - Number(item.requiredLabelNum)
          if (Number(this.addTableData[index].detailNum) < trueNum) {
            trueNumBoo = false
          }
        }
      })
      await this.optimizeNewhandleSaveFour(trueNumBoo)
      // if (!trueNumBoo) {
      //   return msgInfoEl({
      //     type: 'error',
      //     message: '该物资下存在已贴签数据，请手动在明细中进行删除'
      //   })
      // }

      // if (this.addTableDataRules(data)) {
      //   return
      // }
      await this.optimizeNewhandleSaveFive(data)
      const obj = {
        subPrjId: this.parentRow.subPrjId,
        sumMoney: this.parentRow.sumMoney,
        prjId: this.parentRow.prjId,
        type: this.parentRow.type,
        materialCode: this.parentRow.pmsServiceCode,
        dataList: this.addTableData.map(item => {
          delete item.childrenData
          return item
        })
      }
      // 保存
      const url =await this.optimizeNewhandleSaveEight()
      this.saveObj.urls = url
      this.saveObj.objdata = obj
      const yueshu = this.addTableData.reduce((sum, item) => Number(sum) + Number(item.detailProportion), 0)
      await this.optimizeNewhandleSaveSix(yueshu)
      const resSave = await saveDetails(obj, url)
      await this.optimizeNewhandleSaveSeven(resSave)
      msgInfoEl({
        type: 'success',
        message: resSave.message
      })
      this.getList()
      this.getAddList()
    },
    async querenClick(check) {
      this.querenvisible = false
      const { urls, objdata } = this.saveObj
      if (check) {
        const resSave = await saveDetails(objdata, urls)
        if (+resSave.code === 4120) {
          this.getList()
          this.getAddList()
          return
        }
        if (resSave.code !== '200') {
          return
        }
        msgInfoEl({
          type: 'success',
          message: resSave.message
        })
        this.getList()
        this.getAddList()
      }
    },
    // 校验
    addTableDataRules(data) {
      const sum = data.reduce((prev, cur) => { return Number(prev) + Number(cur) })
      if (sum > 100) {
        return msgInfoEl({
          type: 'error',
          message: '总占比不能超过100'
        })
      }

      // 砖混/框架机房校验
      if (this.parentRow.type === '3') {
        if (this.addTableData.length > 1) {
          return msgInfoEl({
            type: 'error',
            message: '砖混/框架机房服务只能配置一种物资编码'
          })
        }
        if (+this.addTableData[0].detailNum !== 1) {
          return msgInfoEl({
            type: 'error',
            message: '砖混/框架机房服务明细数量只能为1'
          })
        }
        if (+this.addTableData[0].detailProportion !== 100) {
          return msgInfoEl({
            type: 'error',
            message: '砖混/框架机房服务明细占比需为100'
          })
        }
      }
    },
    saveRules(value, row, name) {
      if (name === 'detailNum') {
        if (!inputValidation(value, row)) {
          msgInfoEl({
            type: 'warning',
            message: `明细物料编码为${row.detailMaterialCode}的数量可填写到小数点后${chZnNumber[row.spuUnitAcc]}位`
          })
          return true
        }
      }
      if (name === 'detailProportion') {
        const va = `${value}`.match(/^[0-9]+(\.[0-9]{0,2})?$/)
        if (!va) {
          msgInfoEl({
            type: 'warning',
            message: `占比只能填写数字且可填写到小数点后二位`
          })
          return true
        }
      }
    },
    // 合计
    summaryMethods({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        const arr = ['detailMoney', 'detailProportion', 'detailNum']
        if (arr.includes(column.property)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return this.$add(prev, curr)
            } else {
              return ''
            }
          }, 0)
        }
      })

      return sums
    },
    // 填写说明
    handleOpenIllustrate() {
      this.$refs['Illustrate'].handleOpen()
    },
    ynEditquDisAble(row, name) {
      let boo = false
      if (name === 'detailNum' && row.sourceType === 'APP') {
        boo = true
      }
      return boo
    },
    shineAsk
  }
}
</script>
<style lang="scss" scoped>
::v-deep .inputTable .el-input__inner {
  text-align: center;
  height: 20px;
}

::v-deep .inputTable .el-input {
  height: 20px;
}

.search-btn {
  margin-top: 10px;
}

.select-form {
  display: flex;
  justify-content: space-between;

  .el-form-item {
    width: 35%;
  }
}

.box {
  border: 1px solid #EBEEF5;
}

.text-content {
  text-align: left;
  line-height: 30px;
}
</style>
